import 'package:flutter/material.dart';
import 'package:gold/base/config.dart';
import 'package:gold/http/api_gold.dart';
import 'package:gold/model/order_model.dart';
import 'package:gold/ui/my/order/recover/online_list_viewmodel.dart';
import 'package:gold/ui/my/order/recover/recover_config.dart';
import 'package:gold/utils/cache_data.dart';
import 'package:gold/utils/res.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';

/// @description: 黄金回收-线上订单列表页面
/// @author tangzhentao
/// @created at 21:32 2024/12/14

class OnlineListPage extends StatefulWidget {
  /// 黄金回收订单状态 [RecoverOrderStatus]
  final String status;

  const OnlineListPage({super.key, required this.status});

  @override
  State<StatefulWidget> createState() => _OnlineListState();
}

class _OnlineListState extends State<OnlineListPage> with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<OnlineListViewmodel>(
        model:  OnlineListViewmodel(ApiGold.recycleList, widget.status),
        onInit: (data) => data.firstLoad(),
        builder: (ctx, order) => SmartRefresher(
          controller: order.controller,
          enablePullUp: true,
          enablePullDown: true,
          onRefresh: () => order.refresh(),
          onLoading: () => order.loadMore(),
          child: ListView.builder(
              itemCount: order.list.length,
              itemBuilder: (_, index) {
                final model = order.list[index];
                final isLast = index == order.list.length - 1;
                final color = model.status == RecoverOrderStatus.done || model.status == RecoverOrderStatus.canceled ? XfgColor.text1D:XfgColor.theme;
                return GestureDetector(
                  onTap: () => order.toDetailPage(index),
                  child: Container(
                    decoration: white10Decoration,
                    margin: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, isLast ? XfgSize().bottomBarHeight:0),
                    child: Column(
                      children: [
                        /// 黄金数量及订单状态
                        Container(
                          height: XfgSize().size49,
                          padding: EdgeInsets.symmetric(horizontal: XfgSize().size12),
                          child: Row(
                            children: [
                              XfgText('黄金料 ${model.weight?? '--'}g', fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.bold),
                              Visibility(
                                visible: model.status == RecoverOrderStatus.canceled,
                                child: Container(
                                  margin: EdgeInsets.only(left: XfgSize().size18),
                                  height: XfgSize().size18,
                                  width: XfgSize().size40,
                                  decoration: BoxDecoration(border: Border.all(color: XfgColor.theme, width: XfgSize().size0_5), borderRadius: BorderRadius.circular(XfgSize().size2)),
                                  alignment: Alignment.center,
                                  child: XfgText(model.refund?.type == RecoverCancelType.personal ? '个人':'平台', fontSize: XfgSize().text12, color: XfgColor.theme),
                                ),
                              ),
                              const Spacer(),
                              XfgText(getRecoverOrderStatusString(model.status?? ''), fontSize: XfgSize().text16,
                                  color: model.status == RecoverOrderStatus.done || model.status == RecoverOrderStatus.canceled ? XfgColor.text3:XfgColor.theme, bold: FontWeight.bold)
                            ],
                          ),
                        ),
                        strokeHeightContainer,
                        /// 金价，预估总价
                        Container(
                          padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size20, XfgSize().size12, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Expanded(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      XfgText('金价', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold),
                                      SizedBox(width: XfgSize().size8),
                                      XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.text1D, bold: FontWeight.bold),
                                      ...getRecoverMoneyWidgets(model.price, XfgColor.text1D)
                                    ],
                                  )
                              ),
                              Expanded(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      XfgText('预估总价', fontSize: XfgSize().text14, color: color, bold: FontWeight.bold),
                                      SizedBox(width: XfgSize().size8),
                                      XfgText('¥', fontSize: XfgSize().text12, color: color, bold: FontWeight.bold),
                                      ...getRecoverMoneyWidgets(model.totalPrice, color)
                                    ],
                                  )
                              ),
                            ],
                          ),
                        ),
                        ..._getStatusWidgets(order, index)
                      ],
                    ),
                  ),
                );
              }
          ),
        )
    );
  }

  /// 获取状态widget列表
  List<Widget> _getStatusWidgets(OnlineListViewmodel viewmodel, int index) {
    final model = viewmodel.list[index];
    final List<Widget> list = [];
    if (model.status == RecoverOrderStatus.unPickUp) {
      /// 待取件
      list.addAll([
        _itemWidget('取件时间', model.pickupTime?? '--', top: XfgSize().size16),
        _itemWidget('取件地址', '${model.address?.address?? ''}${model.address?.houseNumber}'),
        Container(
          padding: EdgeInsets.only(top: XfgSize().size24, bottom: XfgSize().size16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TextButton(
                  onPressed: () => viewmodel.cancelOrder(index),
                  style: xfgButtonStyle(Size(XfgSize().size97, XfgSize().size32), color: XfgColor.background, radius: XfgSize().size32),
                  child: XfgText('取消订单', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)
              ),
              SizedBox(width: XfgSize().size10),
              TextButton(
                  onPressed: () => viewmodel.expressDelivery(index),
                  style: xfgButtonStyle(Size(XfgSize().size112, XfgSize().size32), radius: XfgSize().size32),
                  child: XfgText('自行寄回快递', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
              ),
              SizedBox(width: XfgSize().size10)
            ],
          ),
        )
      ]);
    } else if (model.status == RecoverOrderStatus.unReceipt) {
      /// 待收件
      list.addAll([
        _itemWidget('下单时间', model.createdAt?? '--', top: XfgSize().size16),
        _itemWidget('发货时间', model.shipmentAt?? '--'),
        SizedBox(height: XfgSize().size14),
        strokeHeightContainer,
        _logisticsWidget(viewmodel, index),
      ]);
    } else if (model.status == RecoverOrderStatus.unVerify) {
      /// 待核件
      list.addAll([
        _itemWidget('下单时间', model.createdAt?? '--', top: XfgSize().size16),
        _itemWidget('发货时间', model.shipmentAt?? '--'),
        _itemWidget('签收时间', model.receiptAt?? '--'),
        SizedBox(height: XfgSize().size20),
      ]);
    } else if (model.status == RecoverOrderStatus.unConfirm) {
      /// 待确认
      list.addAll([
        Container(
          padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size18, XfgSize().size12, 0),
          child: Row(
            children: [
              Expanded(child: XfgText('核重   ${model.auditWeight?.toStringAsFixed(2)?? '0'}g', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)),
              Expanded(child: XfgText('保费   ¥${((model.weight?? 0) * (model.price?? 0) * CacheData().collateralRate).toStringAsFixed(2)}', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)),
            ],
          ),
        ),
        Container(
          padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size14, XfgSize().size12, 0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              XfgText('成交总价', fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
              SizedBox(width: XfgSize().size8),
              XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, bold: FontWeight.bold),
              ...getRecoverMoneyWidgets(model.auditTotalPrice, XfgColor.theme)
            ],
          ),
        ),
        _itemWidget('下单时间', model.createdAt?? '--', top: XfgSize().size16),
        _itemWidget('发货时间', model.shipmentAt?? '--'),
        _itemWidget('签收时间', model.receiptAt?? '--'),
        _itemWidget('核件时间', model.auditAt?? '--'),
        Container(
          padding: EdgeInsets.symmetric(horizontal: XfgSize().size14, vertical: XfgSize().size16),
          child: Row(
            children: [
              Expanded(
                child: GestureDetector(
                  onTap: () => viewmodel.viewNuclearMaterialVideo(index),
                  child: XfgText('查看视频资料', fontSize: XfgSize().text14, color: XfgColor.text1, decoration: TextDecoration.underline),
                )
              ),
              SizedBox(width: XfgSize().size10),
              TextButton(
                  onPressed: () => viewmodel.confirmDeal(index),
                  style: xfgButtonStyle(Size(XfgSize().size97, XfgSize().size32), radius: XfgSize().size32),
                  child: XfgText('确认交易', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
              )
            ],
          ),
        )
      ]);
    } else if (model.status == RecoverOrderStatus.done) {
      /// 已完成
      list.addAll([
        Container(
          padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size18, XfgSize().size12, 0),
          child: Row(
            children: [
              Expanded(child: XfgText('核重   ${model.auditWeight?.toStringAsFixed(2)?? '0'}g', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)),
              Expanded(child: XfgText('保费   ¥${((model.weight?? 0) * (model.price?? 0) * CacheData().collateralRate).toStringAsFixed(2)}', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)),
            ],
          ),
        ),
        Container(
          padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size14, XfgSize().size12, 0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              XfgText('成交总价', fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
              SizedBox(width: XfgSize().size8),
              XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, bold: FontWeight.bold),
              ...getRecoverMoneyWidgets(model.auditTotalPrice, XfgColor.theme)
            ],
          ),
        ),
        _itemWidget('下单时间', model.createdAt?? '--', top: XfgSize().size16),
        _itemWidget('发货时间', model.shipmentAt?? '--'),
        _itemWidget('签收时间', model.receiptAt?? '--'),
        _itemWidget('核件时间', model.auditAt?? '--'),
        SizedBox(height: XfgSize().size16)
      ]);
    } else if (model.status == RecoverOrderStatus.canceled) {
      /// 已取消
      final isPersonal = model.refund?.type == RecoverCancelType.personal;
      if (isPersonal) {
        list.addAll([
          _itemWidget('申请时间', model.refund?.createdAt?? '--', top: XfgSize().size16),
          _itemWidget('取消原因', model.refund?.reason?? '--'),
          SizedBox(height: XfgSize().size16)
        ]);
      } else {
        list.addAll([
          _itemWidget('下单时间', model.createdAt?? '--', top: XfgSize().size16),
          _itemWidget('发货时间', model.shipmentAt?? '--'),
          _itemWidget('退回原因', model.refund?.reason?? '暂无'),
          _logisticsWidget(viewmodel, index, isShipLogistics: false),
        ]);
      }
    }
    return list;
  }

  /// 物流信息Widget
  Widget _logisticsWidget(OnlineListViewmodel viewmodel, int index, {bool isShipLogistics = true}) {
    final model = viewmodel.list[index];
    ExpressModel? express = isShipLogistics ? model.express:model.refund?.express;
    String expressDes = express?.expressDetail?.expTextName?? '';
    final expressStatus = getExpressStatusDesc(express?.expressDetail?.status);
    final list = express?.expressDetail?.data;
    if (list?.isNotEmpty == true) {
      expressDes = '$expressDes：${list?.isNotEmpty == true ? list!.first.context?? '':''}';
    }
    return GestureDetector(
      onTap: () => viewmodel.checkLogistics(index, isShipLogistics),
      behavior: HitTestBehavior.opaque,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: XfgSize().size5, vertical: XfgSize().size10),
        padding: EdgeInsets.symmetric(horizontal: XfgSize().size10),
        height: XfgSize().size28,
        decoration: BoxDecoration(color: XfgColor.background, borderRadius: BorderRadius.circular(XfgSize().size2)),
        child: Row(
          children: [
            Image.asset(Res.imagesOrderLogistics, width: XfgSize().size20, height: XfgSize().size15 + XfgSize().size0_5),
            XfgText(' $expressStatus ', fontSize: XfgSize().text12, color: XfgColor.orderLogistics),
            Expanded(child: XfgText(expressDes, fontSize: XfgSize().text12, color: XfgColor.color4F, maxLines: 1, overflow: TextOverflow.ellipsis))
          ],
        ),
      ),
    );
  }

  /// 通用信息Widget
  Widget _itemWidget(String text, String value, {double? top}) => Container(
    padding: EdgeInsets.fromLTRB(XfgSize().size12, top ?? XfgSize().size10, XfgSize().size12, 0),
    child: Row(
      children: [
        XfgText('$text：', fontSize: XfgSize().text14, color: XfgColor.text2),
        Expanded(child: XfgText(value, fontSize: XfgSize().text14, color: XfgColor.text2))
      ],
    ),
  );

  @override
  bool get wantKeepAlive => true;
}
